{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <h2>体育素质管理</h2>
        
        {% if current_user.role == 'student' %}
            <div class="card mt-4">
                <div class="card-header">
                    <h4>提交体育素质评分</h4>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ url_for('submit_physical') }}" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <div class="mb-3">
                            <label class="form-label">学期</label>
                            <select class="form-select" name="semester" required>
                                <option value="">请选择学期</option>
                                <option value="2023-2024">2023-2024</option>
                                <option value="2024-2025">2024-2025</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">体育课程类型</label>
                            <select class="form-select" name="course_type" id="courseType" onchange="handleCourseTypeChange()" required>
                                <option value="">请选择类型</option>
                                <option value="C1">C1 免修体育课（60分）</option>
                                <option value="C2">C2 体测结果</option>
                                <option value="C3">C3 正常体育课</option>
                            </select>
                        </div>

                        <div class="mb-3" id="testResultDiv" style="display: none;">
                            <label class="form-label">体测结果</label>
                            <select class="form-select" name="test_result" id="testResult" onchange="updateScore()">
                                <option value="">请选择体测结果</option>
                                <option value="pass">达标（100分）</option>
                                <option value="fail">不达标（40分）</option>
                                <option value="absent">不参加体测（0分）</option>
                            </select>
                        </div>

                        <div class="b-3" id="C3ScoreDiv" style="display: none;">
                                <label class="form-label">学年体育平均分</label>
                                <input type="number"  class="form-control" name="C3_score" id="C3Score" min="0"  max="100">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">最终得分</label>
                            <input type="number" class="form-control" name="physical_score" id="physicalScore" >
                        </div>

                        <div class="mb-3">
                            <label class="form-label">证明材料（选填）</label>
                            <input type="file" class="form-control" name="proof_file" accept=".pdf,.jpg,.jpeg,.png">
                            <div class="form-text">支持PDF、JPG、PNG格式，大小不超过5MB</div>
                        </div>

                        <button type="submit" class="btn btn-primary">提交评分</button>
                    </form>
                </div>
            </div>

            <!-- 显示历史记录 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>我的体育素质记录</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>课程类型</th>
                                <th>体测结果</th>
                                <th>得分</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in physical_records %}
                            <tr>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.course_type }}</td>
                                <td>{{ record.test_result }}</td>
                                <td>{{ record.physical_score }}</td>
                                <td>
                                    {% if record.status == 'pending' %}
                                        <span class="badge bg-warning">待审核</span>
                                    {% elif record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_physical_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% else %}
            <!-- 教师查看界面 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>待审核体育成绩</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>课程类型</th>
                                <th>体测结果</th>
                                <th>得分</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>附件</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in physical_records %}
                            {% if record.status == 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.course_type }}</td>
                                <td>{{ record.test_result }}</td>
                                <td>{{ record.physical_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <span class="badge bg-warning">待审核</span>
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_physical_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-success" onclick="approveScore('physical', {{ record.id }})">通过</button>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="rejectScore('physical', {{ record.id }})">驳回</button>
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 已审核成绩表格 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>已审核体育成绩</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>课程类型</th>
                                <th>体测结果</th>
                                <th>得分</th>
                                <th>提交时间</th>
                                <th>审核时间</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in physical_records %}
                            {% if record.status != 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.course_type }}</td>
                                <td>{{ record.test_result }}</td>
                                <td>{{ record.physical_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>{{ record.update_time.strftime('%Y-%m-%d %H:%M') if record.update_time else '' }}</td>
                                <td>
                                    {% if record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_physical_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<script>
function handleCourseTypeChange() {
    const courseType = document.getElementById('courseType').value;
    const testResultDiv = document.getElementById('testResultDiv');
    const testResult = document.getElementById('testResult');
    const scoreInput = document.getElementById('physicalScore');
    
    if (courseType === 'C1') {
        testResultDiv.style.display = 'none';
        testResult.value = '';
        scoreInput.value = '60';
    } else if (courseType === 'C2') {
        testResultDiv.style.display = 'block';
        scoreInput.value = '';
    } else {
        testResultDiv.style.display = 'none';
        testResult.value = '';
        scoreInput.value = '';
    }
}

function updateScore() {
    const testResult = document.getElementById('testResult').value;
    const scoreInput = document.getElementById('physicalScore');
    
    switch(testResult) {
        case 'pass':
            scoreInput.value = '100';
            break;
        case 'fail':
            scoreInput.value = '40';
            break;
        case 'absent':
            scoreInput.value = '0';
            break;
        default:
            scoreInput.value = '';
    }
}

function approveScore(type, recordId) {
    if (confirm('确定要通过这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        fetch(`/approve_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('审核通过成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}

function rejectScore(type, recordId) {
    if (confirm('确定要驳回这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        fetch(`/reject_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('驳回成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}
</script>
{% endblock %} 